package com.yjz.study.ui.fragment

import android.content.res.Configuration
import android.os.Bundle
import android.view.View
import androidx.lifecycle.ViewModelProvider
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.yjz.common.base.AbsListFragment
import com.yjz.common.restful.annotation.CacheStrategy
import com.yjz.common.util.FoldableDeviceUtil
import com.yjz.study.adapter.home.BannerItem
import com.yjz.study.adapter.home.GoodsItem
import com.yjz.study.adapter.home.GridItem
import com.yjz.study.http.entity.res.HomeModel
import com.yjz.study.viewmodel.HomeViewModel
import com.yjz.ui.recycler.item.HiDataItem

/**
 *作用 : 首页tabFragment
 *作者 : yjz
 *时间 : 2025/3/13 16:16
 */
class HomeTabFragment : AbsListFragment() {
    private var categoryId: String? = null
    private lateinit var viewModel: HomeViewModel


    companion object {

        const val CATEGORY_ID = "categoryId"
        const val DEFAULT_CATEGORY_ID = "1"

        fun newInstance(categoryId: String): HomeTabFragment {
            val bundle = Bundle()
            bundle.putString(CATEGORY_ID, categoryId)
            val homePageFragment = HomeTabFragment()
            homePageFragment.arguments = bundle
            return homePageFragment
        }
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        categoryId = arguments?.getString(CATEGORY_ID, DEFAULT_CATEGORY_ID)
        super.onViewCreated(view, savedInstanceState)
        viewModel = ViewModelProvider(this)[HomeViewModel::class.java]
        queryTabCategoryList(CacheStrategy.CACHE_FIRST)
        enableLoadMore {
            queryTabCategoryList(CacheStrategy.NET_ONLY)
        }
    }

    override fun createLayoutManager(): RecyclerView.LayoutManager {
        val isHotTab = android.text.TextUtils.equals(categoryId, DEFAULT_CATEGORY_ID)
        return if (isHotTab) super.createLayoutManager() else GridLayoutManager(context, 2)
    }

    override fun onRefresh() {
        super.onRefresh()
        queryTabCategoryList(CacheStrategy.NET_CACHE)
    }

    /**
     * 查询分类的数据
     * @param strategy 缓存策略
     */
    private fun queryTabCategoryList(strategy: Int) {
        viewModel.queryTabCategoryList(categoryId!!, pageIndex, strategy).observe(viewLifecycleOwner) {
            if (it != null) {
                updateUI(it)
            } else {
                finishRefresh(null)
            }
        }
    }

    private fun updateUI(data: HomeModel) {
        if (!isAlive) return
        val dataItems = mutableListOf<HiDataItem<*, *>>()
        data.bannerList?.let {
            dataItems.add(BannerItem(data.bannerList))
        }

        data.subcategoryList?.let {
            dataItems.add(GridItem(data.subcategoryList))
        }

        data.goodsList?.forEachIndexed { index, goodsModel ->
            dataItems.add(
                GoodsItem(
                    goodsModel,
                    android.text.TextUtils.equals(categoryId, DEFAULT_CATEGORY_ID)
                )
            )
        }
        finishRefresh(dataItems)
    }

    override fun onConfigurationChanged(newConfig: Configuration) {
        super.onConfigurationChanged(newConfig)
        /*折叠屏展开时为grid*/
        if (FoldableDeviceUtil.isFold()) {
            recyclerView?.layoutManager = LinearLayoutManager(context)
        } else {
            val manager = GridLayoutManager(context, 2)
            manager.spanSizeLookup = object : GridLayoutManager.SpanSizeLookup() {
                override fun getSpanSize(position: Int): Int {
                    return if (position <= 1) 2 else 1
                }
            }
            recyclerView?.layoutManager = manager
        }
    }
}